package com.binhthuan.catechist.server;

import java.io.File;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.binhthuan.catechist.server.util.preferences.ConfigLoader;
import com.binhthuan.catechist.server.util.preferences.SystemGlobals;
import com.binhthuan.catechist.shared.constant.Parameter;

public class CentralServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 697636666243836557L;
    private ApplicationContext serviceContext;

    @Override
    public void init(ServletConfig config) throws ServletException {
        serviceContext = new ClassPathXmlApplicationContext("serviceContext.xml");
        ServletContext context = config.getServletContext();
        String appPath = context.getRealPath("");
        System.out.println("Application path: " + appPath);
        String configPath = context.getRealPath(context.getInitParameter("configurations"));
        ConfigLoader.startSystemglobals(appPath, configPath);
        ConfigLoader.startCacheEngine();
        ConfigLoader.listenForChanges();
        initUploadFolder();
        super.init(config);
    }

    private void initUploadFolder() {
        File uploadFolder = new File(SystemGlobals.getApplicationUploadDir());
        File tempFolder = new File(SystemGlobals.getApplicationUploadTempDir());

        if (!uploadFolder.exists()) {
            uploadFolder.mkdirs();
        }

        if (!tempFolder.exists()) {
            tempFolder.mkdirs();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        String serviceType = request.getParameter(Parameter.SERVICE);
        RequestDispatcher dispatcher = getServletContext().getNamedDispatcher(serviceType);
        if (dispatcher != null) {
            dispatcher.forward(request, response);
        }
        System.out.println(serviceType);
    }
}
